<template>
	<view class="port-products-container">
		<!-- 自定义导航栏 -->
		<ob-navbar
			:title="portInfo.name ? `${portInfo.name} - 商品列表` : '港口商品'"
			:show-back="true"
			background-color="#FFFFFF"
			title-color="#333333"
			:border="true"
		/>

		<!-- 港口信息卡片 -->
		<view v-if="portInfo.id" class="port-info-card">
			<view class="port-header">
				<view class="port-basic">
					<text class="port-name">{{ portInfo.name }}</text>
					<text class="port-code">{{ portInfo.portCode }}</text>
				</view>
				<view class="port-stats">
					<text class="product-count">{{ totalCount }}种商品</text>
					<text v-if="portInfo.country" class="country-name">{{ portInfo.country.name }}</text>
				</view>
			</view>
			<text v-if="portInfo.description" class="port-desc">{{ portInfo.description }}</text>
		</view>

		<!-- 搜索框 -->
		<view class="search-section">
			<view class="search-box">
				<text class="search-icon">🔍</text>
				<input
					class="search-input"
					type="text"
					v-model="searchKeyword"
					placeholder="搜索商品名称"
					@input="onSearchInput"
					@confirm="searchProducts"
				/>
				<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">✕</text>
			</view>
		</view>

		<!-- 筛选排序栏 -->
		<view class="filter-bar">
			<view 
				v-for="(filter, index) in filterOptions" 
				:key="index"
				class="filter-item"
				:class="{ 'filter-active': selectedSort === filter.value }"
				@click="selectSort(filter.value)"
			>
				<text class="filter-text">{{ filter.label }}</text>
				<text v-if="filter.value === 'price_asc' || filter.value === 'price_desc'" class="filter-arrow">
					{{ filter.value === 'price_asc' ? '↑' : '↓' }}
				</text>
			</view>
		</view>

		<!-- 商品列表 -->
		<scroll-view class="product-scroll" scroll-y="true" @scrolltolower="loadMore">
			<view v-if="products.length > 0" class="product-grid">
				<view
					v-for="(product, index) in products"
					:key="product.productId"
					class="product-item"
					@click="goToProduct(product)"
				>
					<!-- 商品图片 -->
					<view class="product-image">
						<image
							v-if="product.coverImage"
							:src="product.coverImage"
							class="product-img"
							mode="aspectFill"
						/>
						<view v-else class="image-placeholder">
							<text class="image-icon">📦</text>
						</view>
						
						<!-- 折扣标签 -->
						<view v-if="product.discountRate && product.discountRate > 0" class="discount-tag">
							<text class="discount-text">{{ Math.floor(product.discountRate) }}折</text>
						</view>
					</view>

					<!-- 商品信息 -->
					<view class="product-info">
						<text class="product-name">{{ product.name }}</text>
						
						<view class="product-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ product.price }}</text>
							<text v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">
								¥{{ product.originalPrice }}
							</text>
						</view>
						
						<view class="product-stats">
							<text class="stats-text">已售{{ product.salesCount || 0 }}件</text>
							<view v-if="product.avgScore" class="rating">
								<text class="rating-icon">⭐</text>
								<text class="rating-value">{{ product.avgScore }}</text>
							</view>
						</view>
					</view>

					<!-- 添加到购物车按钮 -->
					<view class="add-cart-btn" @click.stop="addToCart(product)">
						<text class="cart-icon">🛒</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-else-if="!isLoading" class="empty-state">
				<text class="empty-icon">📦</text>
				<text class="empty-text">{{ searchKeyword ? '没有找到相关商品' : '该港口暂无商品' }}</text>
				<text v-if="searchKeyword" class="empty-tip">试试其他关键词</text>
			</view>
			
			<!-- 加载更多 -->
			<view v-if="hasMore && products.length > 0" class="load-more">
				<text class="load-text">{{ isLoading ? '加载中...' : '上拉加载更多' }}</text>
			</view>
			
			<!-- 没有更多 -->
			<view v-else-if="products.length > 0 && !hasMore" class="no-more">
				<text class="no-more-text">已显示全部商品</text>
			</view>
		</scroll-view>

		<!-- 热门推荐区域 -->
		<view class="recommend-section">
			<view class="section-header">
				<text class="section-title">🔥 热门推荐</text>
				<view class="recommend-controls">
					<text class="refresh-btn" @click="refreshRecommend">刷新</text>
				</view>
			</view>
			
			<view v-if="recommendProducts.length > 0" class="recommend-grid">
				<view 
					v-for="(product, index) in recommendProducts"
					:key="product.id"
					class="recommend-item"
					@click="goToProduct(product)"
				>
					<view class="product-image">
						<image
							v-if="product.image"
							:src="product.image"
							class="product-img"
							mode="aspectFill"
							@error="handleImageError(product)"
						/>
						<view v-else class="image-placeholder">
							<text class="image-icon">📦</text>
						</view>
					</view>
					
					<view class="product-info">
						<text class="product-name">{{ product.name }}</text>
						<view class="product-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ product.price }}</text>
							<text v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">
								¥{{ product.originalPrice }}
							</text>
						</view>
						<view class="product-stats">
							<text v-if="product.sales" class="stats-text">已售{{ product.sales }}件</text>
							<view v-if="product.rating" class="rating">
								<text class="rating-star">⭐</text>
								<text class="rating-value">{{ product.rating }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 推荐商品空状态 -->
			<view v-else-if="!isLoadingRecommend" class="empty-recommend">
				<text class="empty-icon">🌟</text>
				<text class="empty-text">暂无推荐商品</text>
			</view>
			
			<!-- 加载更多推荐 -->
			<view v-if="hasMoreRecommend && recommendProducts.length > 0" class="load-more-recommend">
				<text class="load-text" @click="loadMoreRecommend">
					{{ isLoadingMoreRecommend ? '加载中...' : '查看更多推荐' }}
				</text>
			</view>
		</view>

		<!-- 加载中遮罩 -->
		<ob-loading :visible="isLoading && products.length === 0" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { debounce } from '../../utils/common.js'
import indexApi from '../../api/indexApi.js'
import cartApi from '../../api/cart.js'
import productApi from '../../api/product.js'

// 全局状态
const store = inject('$store')

// 页面参数
const portId = ref('')
const portName = ref('')
const portCode = ref('')

// 响应式数据
const portInfo = ref({})
const products = ref([])
const searchKeyword = ref('')
const selectedSort = ref('score_desc')
const isLoading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(12)
const totalCount = ref(0)

// 热门推荐相关数据
const recommendProducts = ref([])
const isLoadingRecommend = ref(false)
const isLoadingMoreRecommend = ref(false)
const hasMoreRecommend = ref(true)

// 筛选选项
const filterOptions = ref([
	{ label: '综合排序', value: 'score_desc' },
	{ label: '销量优先', value: 'sales_desc' },
	{ label: '价格↑', value: 'price_asc' },
	{ label: '价格↓', value: 'price_desc' }
])

// 页面参数处理
onLoad((options) => {
	console.log('港口商品页面参数:', options)
	
	if (options.portId) {
		portId.value = options.portId
		
		// 接收传入的港口信息，用于优化用户体验
		if (options.portName) {
			portName.value = decodeURIComponent(options.portName)
			// 先用传入的信息初始化，避免空白
			portInfo.value = {
				...portInfo.value,
				name: portName.value
			}
		}
		
		if (options.portCode) {
			portCode.value = decodeURIComponent(options.portCode)
			portInfo.value = {
				...portInfo.value,
				portCode: portCode.value
			}
		}
		
		// 重置数据并加载
		resetData()
		loadPortProducts()
		
		// 加载热门推荐
		loadRecommendProducts(true)
	} else {
		uni.showToast({
			title: '缺少港口参数',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
})

// 页面加载
onMounted(() => {
	// onLoad会在onMounted之前执行，这里作为备用
	if (!portId.value) {
		console.log('未获取到portId')
	}
})

// 重置数据
const resetData = () => {
	products.value = []
	currentPage.value = 1
	hasMore.value = true
	isLoading.value = false
	totalCount.value = 0
}

// 加载港口商品
const loadPortProducts = async (isLoadMore = false) => {
	if (isLoading.value || !portId.value) return

	try {
		isLoading.value = true

		if (!isLoadMore) {
			currentPage.value = 1
			products.value = []
		}

		const params = {
			page: currentPage.value,
			size: pageSize.value,
			sortBy: selectedSort.value
		}

		// 添加搜索关键词
		if (searchKeyword.value.trim()) {
			params.keyword = searchKeyword.value.trim()
		}

		console.log('请求港口商品参数:', params)

		const response = await indexApi.getPortProducts(portId.value, params)
		console.log('港口商品响应:', response)

		if (response && response.products) {
			// 处理商品数据，确保格式正确
			const processedProducts = response.products.map(product => {
				// 处理图片数据
				let imageUrl = '/static/images/product-placeholder.jpg'; // 默认图片
				
				if (product.images && Array.isArray(product.images) && product.images.length > 0) {
					// 如果有images数组，取第一张图片
					const firstImage = product.images[0];
					if (firstImage && firstImage.imageUrl) {
						imageUrl = firstImage.imageUrl.startsWith('http') 
							? firstImage.imageUrl 
							: `http://8.145.55.161:19000${firstImage.imageUrl}`;
					}
				} else if (product.pic) {
					// 如果有pic字段，使用pic
					imageUrl = product.pic.startsWith('http') 
						? product.pic 
						: `http://8.145.55.161:19000${product.pic}`;
				}

				return {
					id: product.productId || product.id,
					name: product.name,
					image: imageUrl,
					price: product.discountPrice || product.price,
					originalPrice: product.price,
					sales: product.salesCount,
					rating: product.avgScore,
					spec: product.shortDescription,
					inventory: product.inventory,
					// 保留原始数据
					...product
				};
			});

			if (isLoadMore) {
				products.value = [...products.value, ...processedProducts]
			} else {
				products.value = processedProducts
				// 更新港口信息
				if (response.port) {
					portInfo.value = response.port
				}
			}

			// 更新分页信息
			totalCount.value = response.totalCount || 0
			hasMore.value = response.hasNext || false
		}

	} catch (error) {
		console.error('加载港口商品失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

// 搜索相关
const onSearchInput = debounce(() => {
	searchProducts()
}, 500)

const searchProducts = () => {
	resetData()
	loadPortProducts()
}

const clearSearch = () => {
	searchKeyword.value = ''
	searchProducts()
}

// 排序选择
const selectSort = (sortValue) => {
	if (selectedSort.value === sortValue) return
	
	selectedSort.value = sortValue
	resetData()
	loadPortProducts()
}

// 加载更多
const loadMore = () => {
	if (!isLoading.value && hasMore.value) {
		currentPage.value++
		loadPortProducts(true)
	}
}

// 页面跳转
const goToProduct = (product) => {
	const productId = product.productId || product.id
	if (productId) {
	uni.navigateTo({
			url: `/pages/product/detail?id=${productId}`
		})
	} else {
		console.error('商品ID不存在:', product)
		uni.showToast({
			title: '商品信息有误',
			icon: 'none'
	})
	}
}

// 添加到购物车
const addToCart = async (product) => {
	try {
		// 调用购物车API
		await cartApi.addToCart({
			productId: product.productId,
			quantity: 1,
			specs: {} // 默认规格，实际应该根据商品规格处理
		})
		
		uni.showToast({
			title: '已添加到购物车',
			icon: 'success',
			duration: 1500
		})
		
		// 更新全局购物车状态
		if (store && store.actions && store.actions.updateCartCount) {
			store.actions.updateCartCount()
		}
		
	} catch (error) {
		console.error('添加到购物车失败:', error)
		uni.showToast({
			title: '添加失败，请重试',
			icon: 'none'
		})
	}
}

// 热门推荐相关函数
// 加载热门推荐商品
const loadRecommendProducts = async (reset = false) => {
	try {
		if (reset) {
			recommendProducts.value = []
		}
		
		isLoadingRecommend.value = true
		
		// 调用后端：获取评分4.7及以上的高评分商品
		const response = await productApi.getHighScoreProducts()
		
		// 统一数据结构
		const list = Array.isArray(response)
			? response
			: (response?.products || response?.list || response?.data || [])
		
		// 辅助：将图片路径补全为可访问URL
		const toUrl = (img) => {
			if (!img) return ''
			if (typeof img === 'string' && img.includes(',')) img = img.split(',')[0].trim()
			if (typeof img !== 'string') img = String(img || '')
			return img.startsWith('http') ? img : `http://8.145.55.161:19000${img.startsWith('/') ? img : '/' + img}`
		}
		
		// 映射到产品卡片所需字段
		const products = (list || []).map(item => ({
			id: item.productId || item.id,
			name: item.name || item.productName,
			price: item.price || 0,
			originalPrice: item.originalPrice,
			image: toUrl(item.coverImage || item.pic || item.image || item.thumbnail),
			sales: item.salesCount || item.sales,
			rating: item.avgScore || item.rating
		}))
		
		recommendProducts.value = products
		
		// 高评分列表通常不分页
		hasMoreRecommend.value = false
		
	} catch (error) {
		console.error('加载推荐商品失败:', error)
		uni.showToast({
			title: '加载推荐商品失败',
			icon: 'none'
		})
	} finally {
		isLoadingRecommend.value = false
	}
}

// 刷新推荐商品
const refreshRecommend = async () => {
	await loadRecommendProducts(true)
	uni.showToast({
		title: '刷新成功',
		icon: 'success',
		duration: 1500
	})
}

// 加载更多推荐商品
const loadMoreRecommend = async () => {
	if (isLoadingMoreRecommend.value || !hasMoreRecommend.value) return
	
	isLoadingMoreRecommend.value = true
	try {
		await loadRecommendProducts(false)
	} finally {
		isLoadingMoreRecommend.value = false
	}
}

// 处理图片加载错误
const handleImageError = (product) => {
	product.image = ''
}
</script>

<style lang="scss" scoped>
.port-products-container {
	background: #F5F7FA;
	min-height: 100vh;
}

// 港口信息卡片
.port-info-card {
	background: #FFFFFF;
	margin: 12px;
	border-radius: 12px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

	.port-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 8px;

		.port-basic {
			.port-name {
				font-size: 18px;
				font-weight: 600;
				color: #1F2937;
				display: block;
				margin-bottom: 4px;
			}

			.port-code {
				font-size: 14px;
				color: #6B7280;
				background: #F3F4F6;
				padding: 2px 8px;
				border-radius: 4px;
			}
		}

		.port-stats {
			text-align: right;

			.product-count {
				font-size: 16px;
				font-weight: 600;
				color: #059669;
				display: block;
				margin-bottom: 4px;
			}

			.country-name {
				font-size: 12px;
				color: #6B7280;
			}
		}
	}

	.port-desc {
		font-size: 14px;
		color: #6B7280;
		line-height: 1.5;
	}
}

// 搜索框
.search-section {
	background: #FFFFFF;
	padding: 12px;
	margin: 0 12px 8px;
	border-radius: 12px;

	.search-box {
		background: #F9FAFB;
		border: 1px solid #E5E7EB;
		border-radius: 8px;
		height: 44px;
		display: flex;
		align-items: center;
		padding: 0 12px;
		gap: 8px;

		.search-icon {
			color: #6B7280;
			font-size: 16px;
		}

		.search-input {
			flex: 1;
			font-size: 14px;
			color: #1F2937;
		}

		.clear-icon {
			color: #9CA3AF;
			padding: 4px;
			font-size: 14px;
		}
	}
}

// 筛选排序栏
.filter-bar {
	background: #FFFFFF;
	display: flex;
	padding: 0 12px;
	margin: 0 12px 8px;
	border-radius: 12px;

	.filter-item {
		flex: 1;
		text-align: center;
		padding: 12px 8px;
		border-bottom: 2px solid transparent;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 4px;

		.filter-text {
			font-size: 14px;
			color: #6B7280;
		}

		.filter-arrow {
			font-size: 12px;
			color: #6B7280;
		}

		&.filter-active {
			border-bottom-color: #3B82F6;

			.filter-text,
			.filter-arrow {
				color: #3B82F6;
				font-weight: 500;
			}
		}
	}
}

// 商品列表
.product-scroll {
	height: calc(100vh - 280px);
}

.product-grid {
	display: flex;
	flex-wrap: wrap;
	padding: 0 8px;
	gap: 8px;
}

.product-item {
	width: calc(50% - 4px);
	background: #FFFFFF;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	position: relative;

	.product-image {
		position: relative;
		width: 100%;
		height: 160px;

		.product-img {
			width: 100%;
			height: 100%;
		}

		.image-placeholder {
			width: 100%;
			height: 100%;
			background: #F3F4F6;
			display: flex;
			align-items: center;
			justify-content: center;

			.image-icon {
				font-size: 32px;
				color: #9CA3AF;
			}
		}

		.discount-tag {
			position: absolute;
			top: 8px;
			left: 8px;
			background: #EF4444;
			border-radius: 4px;
			padding: 2px 6px;

			.discount-text {
				color: #FFFFFF;
				font-size: 10px;
				font-weight: 600;
			}
		}
	}

	.product-info {
		padding: 12px;

		.product-name {
			font-size: 14px;
			color: #1F2937;
			line-height: 1.4;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			margin-bottom: 8px;
		}

		.product-price {
			display: flex;
			align-items: baseline;
			gap: 4px;
			margin-bottom: 8px;

			.price-symbol {
				font-size: 12px;
				color: #EF4444;
				font-weight: 600;
			}

			.price-value {
				font-size: 16px;
				color: #EF4444;
				font-weight: 600;
			}

			.original-price {
				font-size: 12px;
				color: #9CA3AF;
				text-decoration: line-through;
			}
		}

		.product-stats {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.stats-text {
				font-size: 12px;
				color: #6B7280;
			}

			.rating {
				display: flex;
				align-items: center;
				gap: 2px;

				.rating-icon {
					font-size: 12px;
				}

				.rating-value {
					font-size: 12px;
					color: #6B7280;
				}
			}
		}
	}

	.add-cart-btn {
		position: absolute;
		bottom: 12px;
		right: 12px;
		width: 32px;
		height: 32px;
		background: #3B82F6;
		border-radius: 16px;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);

		.cart-icon {
			color: #FFFFFF;
			font-size: 14px;
		}
	}
}

// 空状态
.empty-state {
	text-align: center;
	padding: 60px 20px;

	.empty-icon {
		font-size: 48px;
		display: block;
		margin-bottom: 16px;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 16px;
		color: #6B7280;
		display: block;
		margin-bottom: 8px;
	}

	.empty-tip {
		font-size: 14px;
		color: #9CA3AF;
	}
}

// 加载更多
.load-more {
	text-align: center;
	padding: 20px;

	.load-text {
		font-size: 14px;
		color: #6B7280;
	}
}

.no-more {
	text-align: center;
	padding: 20px;

	.no-more-text {
		font-size: 14px;
		color: #9CA3AF;
	}
}

// 热门推荐区域样式
.recommend-section {
	background: #FFFFFF;
	margin: 12px;
	border-radius: 12px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;

		.section-title {
			font-size: 18px;
			font-weight: 600;
			color: #1F2937;
		}

		.recommend-controls {
			.refresh-btn {
				font-size: 14px;
				color: #3B82F6;
				padding: 4px 8px;
				border-radius: 4px;
				background: #EFF6FF;
			}
		}
	}

	.recommend-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 12px;

		.recommend-item {
			background: #FAFBFC;
			border-radius: 8px;
			padding: 8px;

			.product-image {
				position: relative;
				width: 100%;
				height: 120px;
				margin-bottom: 8px;

				.product-img {
					width: 100%;
					height: 100%;
					border-radius: 6px;
				}

				.image-placeholder {
					width: 100%;
					height: 100%;
					background: #F3F4F6;
					border-radius: 6px;
					display: flex;
					align-items: center;
					justify-content: center;

					.image-icon {
						font-size: 24px;
						opacity: 0.5;
					}
				}
			}

			.product-info {
				.product-name {
					font-size: 14px;
					color: #1F2937;
					font-weight: 500;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
					line-height: 1.3;
					height: 36px;
					margin-bottom: 8px;
				}

				.product-price {
					display: flex;
					align-items: baseline;
					margin-bottom: 4px;

					.price-symbol {
						font-size: 12px;
						color: #EF4444;
						font-weight: 500;
					}

					.price-value {
						font-size: 16px;
						color: #EF4444;
						font-weight: 600;
						margin-right: 8px;
					}

					.original-price {
						font-size: 12px;
						color: #9CA3AF;
						text-decoration: line-through;
					}
				}

				.product-stats {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.stats-text {
						font-size: 12px;
						color: #6B7280;
					}

					.rating {
						display: flex;
						align-items: center;

						.rating-star {
							font-size: 12px;
							margin-right: 2px;
						}

						.rating-value {
							font-size: 12px;
							color: #F59E0B;
							font-weight: 500;
						}
					}
				}
			}
		}
	}

	.empty-recommend {
		text-align: center;
		padding: 40px 20px;

		.empty-icon {
			font-size: 48px;
			display: block;
			margin-bottom: 16px;
			opacity: 0.5;
		}

		.empty-text {
			font-size: 16px;
			color: #6B7280;
		}
	}

	.load-more-recommend {
		text-align: center;
		padding: 16px;

		.load-text {
			font-size: 14px;
			color: #3B82F6;
			padding: 8px 16px;
			border: 1px solid #3B82F6;
			border-radius: 20px;
			background: #EFF6FF;
		}
	}
}
</style> 